#include <glib/gi18n.h>
#include <gtk/gtk.h>
#include "demo.h"

static gboolean on_draw(GtkWidget *widget, cairo_t *cr, gpointer data)
{
    guint width, height;
    // GdkRGBA color;
    GtkStyleContext *context;


    context = gtk_widget_get_style_context (widget);

    width = gtk_widget_get_allocated_width (widget);
    height = gtk_widget_get_allocated_height (widget);

    g_print("on_draw()....width=%d,height=%d\n", width, height);

    gtk_render_background (context, cr, 0, 0, width, height);


    draw_coord(cr, 0, 0);

    cairo_save(cr);                                 //inside

    //draw outline
    cairo_rectangle(cr, 100, 100, 100, 50);
	cairo_set_source_rgba (cr, 1, 0, 0, 1);
    cairo_set_line_width(cr, 1);
    cairo_stroke(cr);
    cairo_arc(cr, 150, 125, 40, 0, 2*G_PI);
	cairo_set_source_rgba (cr, 0, 1, 0, 1);
    cairo_set_line_width(cr, 1);
    cairo_stroke(cr);

    //draw clip inside
    cairo_rectangle(cr, 100, 100, 100, 50);
    cairo_clip(cr);
    cairo_arc(cr, 150, 125, 40, 0, 2*G_PI);
	cairo_set_source_rgba (cr, 1, 1, 0, 1);
	cairo_fill(cr);
    cairo_restore(cr);


    cairo_save(cr);                                 //outside

    //draw outline

    cairo_rectangle(cr, 300, 100, 100, 50);
	cairo_set_source_rgba (cr, 1, 0, 0, 1);
    cairo_set_line_width(cr, 1);
    cairo_stroke(cr);
    cairo_arc(cr, 350, 125, 40, 0, 2*G_PI);
	cairo_set_source_rgba (cr, 0, 1, 0, 1);
    cairo_set_line_width(cr, 1);
    cairo_stroke(cr);

    //draw clip outside.  outside = 1 - inside
    cairo_rectangle(cr, 300, 100, 100, 50);
    cairo_clip(cr);

    // cairo_rectangle(cr, 0, 0, width, height);
    cairo_rectangle(cr, 400, 100, -100, 50);     //反向path, 适用于CAIRO_FILL_RULE_WINDING
    cairo_new_sub_path(cr);
    cairo_arc(cr, 350, 125, 40, 0, 2*G_PI);
	cairo_set_source_rgba (cr, 1, 1, 0, 1);
	cairo_fill(cr);
    cairo_restore(cr);

    return FALSE;
}

void do_clip(GtkBox *parent)
{
    GtkWidget* frame;
    GtkWidget* drawing_area;

    frame = gtk_frame_new("clip");
    gtk_container_set_border_width(GTK_CONTAINER(frame), 10);
    gtk_box_pack_start(parent, frame, TRUE, TRUE, 0);

    drawing_area = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(frame), drawing_area);

    g_signal_connect(drawing_area, "draw", G_CALLBACK (on_draw), NULL);        

    gtk_widget_show_all(GTK_WIDGET(parent));    
}